package net.rock.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.rock.config.BookConfig;
import net.rock.mapper.BookMapper;
import net.rock.pojo.Book;
import net.rock.utils.MapperUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class BookService {
    @Autowired
    private BookConfig bookConfig;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private JedisCluster cluster;

    private static final ObjectMapper OM = MapperUtil.MP;
    private static final String BOOK_PREFIX = "BOOK_";
    static final int ITEMS_PER_PAGE = 100;

    private static String getBookKey(int id) {
        return String.format("%s%d", BOOK_PREFIX, id);
    }

    // page 从0开始
    public List<Book> fetchBooks(Integer categoryId, Integer page) {
        Integer offset = null;
        if (page != null) {
            offset = page * ITEMS_PER_PAGE;
        }

        return bookMapper.fetchBooks(categoryId, offset);
    }

    public Book fetchBookById(int id) throws IOException {
        String bookJson = cluster.get(getBookKey(id));
        Book book;

        if (StringUtils.isEmpty(bookJson)) {  // 若缓存中没有该商品，则从数据库中获取，并写入缓存
            book = bookMapper.fetchBookById(id);
            if (book != null) {
                bookJson = OM.writeValueAsString(book);
                cluster.set(getBookKey(id), bookJson);
            }
        } else {
            book = OM.readValue(bookJson, Book.class);
        }

        return book;
    }

    public void add(Book book) {
        bookMapper.add(book);
    }

    private void deleteImg(String path) {
        String uploadPath = BookConfig.workDir + bookConfig.getUploadPath() + path;
        File img = new File(uploadPath);

        //noinspection unused
        boolean _a = img.delete();
    }

    public void del(int id) throws IOException {
        Book book = fetchBookById(id);
        String url = book.getImgUrl();
        if (url.startsWith(bookConfig.getImgPath())) {  // 由本地上传的而非来自网络
            String filename = url.substring(bookConfig.getImgPath().length());
            deleteImg(filename);
        }

        bookMapper.del(id);
        cluster.del(getBookKey(id));
    }

    public void edit(Book book) {
        bookMapper.edit(book);
        cluster.del(getBookKey(book.getId()));

    }

    public List<Book> searchBooks(String keyword) {
        return bookMapper.searchBooks(keyword);
    }

}
